package com.fourth.service.impl;

import com.fourth.util.RedisKeyUtils;
import com.fourth.enums.RoleStateEnum;
import com.fourth.service.RedisService;
import com.ljx.entity.Role;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Mr.ma
 * @since 2023/2/28 14:07
 **/
@Service
@Slf4j
public class RedisServiceImpl implements RedisService {

    @Resource
    private RedisTemplate redisTemplate;



    @Override
    public void noRunRedis(String roleID) {
        String roleKey = RedisKeyUtils.getRoleKey("role", roleID);
        redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_ROLE_STATE,roleKey, RoleStateEnum.UNAVAILABLE.getCode());
    }

    @Override
    public void runRedis(String roleID) {
        String roleKey = RedisKeyUtils.getRoleKey("role", roleID);
        redisTemplate.opsForHash().put(RedisKeyUtils.MAP_KEY_ROLE_STATE,roleKey, RoleStateEnum.AVAILABLE.getCode());
    }

    @Override
    public List<Role> getStateDataFromRedis() {
        Cursor<Map.Entry<Object, Object>> scan = redisTemplate.opsForHash().scan(RedisKeyUtils.MAP_KEY_ROLE_STATE, ScanOptions.NONE);
        ArrayList<Role> roles = new ArrayList<>();
        while(scan.hasNext()){
            Map.Entry<Object, Object> entry = scan.next();
            String key = (String) entry.getKey();
            String[] split = key.split("::");
            String roleId = split[1];
            String value = (String) entry.getValue();
            Role role = new Role();
            role.setId(roleId);
            role.setStatus(value);
            roles.add(role);

            redisTemplate.opsForHash().delete(RedisKeyUtils.MAP_KEY_ROLE_STATE,key);
        }
        return roles;
    }
}
